package io.zim.modules.ws.server;

import io.zim.modules.ws.config.ShowcaseServerConfig;
import io.zim.modules.ws.listener.ShowcaseIpStatListener;
import io.zim.modules.ws.listener.ShowcaseServerAioListener;
import io.zim.modules.ws.service.ShowcaseWsMsgHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.tio.server.ServerGroupContext;
import org.tio.websocket.server.WsServerStarter;

/**
 *
 * @author
 * @since
 */
@Component
public class IMServerStarter implements CommandLineRunner {
  private static final Logger LOG = LoggerFactory.getLogger(IMServerStarter.class);
  private WsServerStarter wsServerStarter;
  private ServerGroupContext serverGroupContext;

  public IMServerStarter(){
  }

  public IMServerStarter(int port, ShowcaseWsMsgHandler wsMsgHandler) throws Exception {
    wsServerStarter = new WsServerStarter(port, wsMsgHandler);

    serverGroupContext = wsServerStarter.getServerGroupContext();
    serverGroupContext.setName(ShowcaseServerConfig.PROTOCOL_NAME);
    serverGroupContext.setServerAioListener(ShowcaseServerAioListener.me);

    //设置ip监控
    serverGroupContext.setIpStatListener(ShowcaseIpStatListener.me);
    //设置ip统计时间段
    serverGroupContext.ipStats.addDurations(ShowcaseServerConfig.IpStatDuration.IPSTAT_DURATIONS);

    //设置心跳超时时间
    serverGroupContext.setHeartbeatTimeout(ShowcaseServerConfig.HEARTBEAT_TIMEOUT);
  }

  @Override
  public void run(String... args) throws Exception {
    LOG.info(">>>>>>>>>>>>>>>启动websocket<<<<<<<<<<<<<");
    IMServerStarter appStarter = new IMServerStarter(ShowcaseServerConfig.SERVER_PORT, ShowcaseWsMsgHandler.me);
    appStarter.wsServerStarter.start();
  }
}
